﻿using ATM.Model;
using ATM.Utilities;
using System.Diagnostics.Contracts;

namespace ATM.Components
{
    /// <summary>
    /// Reads inserted credit cards and provides basic input validation.
    /// </summary>
    public class CreditCardReader
    {
        /// <summary>
        /// Attempts to read credit card given amount of time.
        /// </summary>
        /// <param name="attempts">Number of read attempts before give up</param>
        /// <returns>An object representing Credit Card information or null if failed to read credit card</returns>
        internal CreditCardInfo ReadCreditCard(int attempts)
        {
            Contract.Requires(attempts > 0);

            string tempCreditCardNumber = null;
            string tempMonth = null;
            string tempYear = null;

            int attemptNumber = 0;

            bool readSuccessfully = false;
            do
            {
                System.Console.WriteLine(">> CreditCardReader: Reading credit card in progres... Attempt {0}", ++attemptNumber);
                System.Console.Write(">> CreditCardReader: Credit card number: ");
                tempCreditCardNumber = System.Console.ReadLine();
                System.Console.Write(">> CreditCardReader: Valid through months: ");
                tempMonth = System.Console.ReadLine();
                System.Console.Write(">> CreditCardReader: Valid through years: ");
                tempYear = System.Console.ReadLine();
                --attempts;

                if (ValidationUtilities.IsCreditCardNumber(tempCreditCardNumber) && ValidationUtilities.IsMonthNumber(tempMonth) && ValidationUtilities.IsYearNumber(tempYear))
                {
                    readSuccessfully = true;
                }
            } while (attempts > 0 && !readSuccessfully);

            return readSuccessfully ? new CreditCardInfo(tempCreditCardNumber, int.Parse(tempMonth), int.Parse(tempYear)) : null;
        }

    }
}
